<?php

namespace App\Service\UserService;
use App\Model\PssModel\PddGoods;
use App\Model\PssModel\PddToken;
use App\Service\BaseService;
use App\Service\Code\Normal;
use Hyperf\Utils\WaitGroup;
use App\Service\VendorClient\PddApi\ShopPddKttUserApiClient;

/**
 * 拼多多快团团业务
 */
class PddkttService extends BaseService
{
    private $client;
    
    /**
     * 接收消息数据
     * @param string $messageType
     * @param array $data
     */
    public function MessageRev(string $messageType, array $goodsList, array $binfo)
    {
        $shopInfoObj = PddToken::instance()->where('status', 1)->where('auth_type', PddToken::AUTH_TYPE_PDD_KTT)->where('bid', $binfo['bid'])->first();

        if (empty($shopInfoObj)) {
            return Normal::returnCode(Normal::FAIL, '未找到店铺信息');
        }
        
        $shopInfo = $shopInfoObj->toArray();
        $this->client = new ShopPddKttUserApiClient($shopInfo);
        if( !method_exists(PddkttService::class, $messageType) ) {
            return Normal::returnCode(Normal::FAIL, "不支持的方法:{$messageType}");
        }
        return $this->{$messageType}($goodsList, $shopInfo);
    }

    /**
     * 商品全量下架
     * @param array $goods
     * @param array $shop
     * @return mixed
     */
    public function goodsBatchDown(array $goods = [],array $shop)
    {
        //处理下架
        $goodsIdListData = PddGoods::instance()->select(['pdd_goods_id', 'skucode'])->where('bid', $shop['bid'])->get()->toArray();
        if (empty($goodsIdListData)) {
            return Normal::returnCode(Normal::FAIL, '无匹配的商品idList');
        }
        
        $goodsIdsTotalList = array_chunk($goodsIdListData, 50);
        //50个一组调用协程
        foreach ($goodsIdsTotalList as $goodsIdList) 
        {
            $count = count($goodsIdList);
            $wg = new WaitGroup();
            $wg->add($count);
            foreach ($goodsIdList as $goods) 
            {
                co(function () use ($wg, $goods, &$result_update) 
                {
                    $response = $this->client->updateGoodsStatusDown([
                        'goods_id'=>$goods['pdd_goods_id']
                    ]);
                    $wg->done();
                });
            }
            $wg->wait();
        }
        return Normal::returnCode(Normal::SUC, '处理完成');
    }
    
    /**
     * 商品批量下架
     * @param array $goods
     * @param array $shop
     * @return mixed
     */
    public function goodsSkuChange(array $goods = [],array $shop)
    {
        //处理下架
        $goodsIdListData = PddGoods::instance()->whereIn('skucode', $skuCodes)->select(['pdd_goods_id', 'skucode'])->where('bid', $shop['bid'])->get()->toArray();
        if (empty($goodsIdListData)) {
            return Normal::returnCode(Normal::FAIL, '无匹配的商品idList');
        }
        
        $goodsIdsTotalList = array_chunk($goodsIdListData, 50);
        //50个一组调用协程
        foreach ($goodsIdsTotalList as $goodsIdList) 
        {
            $count = count($goodsIdList);
            $wg = new WaitGroup();
            $wg->add($count);
            foreach ($goodsIdList as $goods) {
                co(function () use ($wg, $goods, &$result_update) 
                {
                    $response = $this->client->updateGoodsStatusDown([
                        'goods_id'=>$goods['pdd_goods_id']
                    ]);
                    $wg->done();
                });
            }
            $wg->wait();
        }
        return Normal::returnCode(Normal::SUC, '处理完成');
    }

    /**
     * 商品同步数据功能
     * @param array $goodsList
     * @param array $shop
     * @return unknown[]|string[]|array[]
     */
    public function goodsChange(array $goodsList, array $shop)
    {
        //查询数据
        $goodsChangeList = [];
        foreach ($goodsList as $goodsItem) 
        {
            $skuList    = current($goodsItem['skuList']);
            $storeList  = current($skuList['storeList']);
            $batchInfo  = current($storeList['goods_batch_list']);
            $specInfo   = current($batchInfo['spec_list']);
            $skuCode    = $batchInfo['supplier_skucode'];
            //拼装商品数组
            $goodsChangeList[$skuCode] = 
            [
                'skucode'       => $skuCode,
                'quantity'      => $batchInfo['num'],
                'price'         => $specInfo['price'],
                'origin_price'  => $specInfo['priceMarket'],
                'title'         => $goodsItem['goodsName'],
                'costPrice'     => $specInfo['priceSettlement'],
                'goods_type'    => $goodsItem['goodsType'],
                'images'        => $goodsItem['images'],
            ];
        }
        
        $skuCodeArr = array_keys($goodsChangeList);
        $authSkuGoods = PddGoods::instance()->whereIn('skucode', $skuCodeArr)->where('bid', $shop['bid'])->get()->toArray();

        //这里需要判断是否已存在数据
        $pddGoodsMap = array_column($authSkuGoods, NULL, 'skucode');
        $pddIsExistGoodsSkuCode = array_keys($pddGoodsMap);
        $insertMysqlDatas = [];
        
        $count = count($goodsChangeList);
        $wg = new WaitGroup();
        $wg->add($count);
        
        //判断是否已经存在拼多多快团团平台
        foreach ($goodsChangeList as $goodsChange) 
        {
            //协程处理
            co(function () use ($wg, $goodsChange,$pddIsExistGoodsSkuCode,$pddGoodsMap,$shop, &$result_update,&$insertMysqlDatas) 
            {
                if (in_array($goodsChange['skucode'], $pddIsExistGoodsSkuCode)) 
                {
                    //修改商品
                    $this->editGoods($goodsChange, $pddGoodsMap[$goodsChange['skucode']], $shop);
                    //上架商品
                    $this->client->updateGoodsStatusUp([
                        'goods_id'=>$pddGoodsMap[$goodsChange['skucode']]['pdd_goods_id']
                    ]);
                }
                else
                {
                    //新增商品
                    $insertResult = $this->insertGoods($goodsChange);
                    if ($insertResult['code'] == Normal::SUC) {
                        $insertMysqlDatas[] = [
                            'skucode'       => $goodsChange['skucode'],
                            'pdd_goods_id'  => $insertResult['data']['goods_id'],
                            'bid'           => $shop['bid']
                        ];
                    }
                }
                $wg->done();
            });
        }
        
        //判断是否有需要添加的数据
        if (!empty($insertMysqlDatas)) 
        {
            PddGoods::instance()->insert($insertMysqlDatas);
        }
        return Normal::returnCode(Normal::SUC, '处理完成');
    }

    private function insertGoods($goods)
    {
        $data = [
            'cat_id'         => 18491,
            'out_goods_id'   => $goods['skucode'],
            'goods_name'     => $goods['title'],
            // 'sku_list'       => json_encode([
            //     [
            //         'is_onsale' => 1,
            //         'limit_quantity' => 999, //sku购买限制，只入参999
            //         'price' => (float)$goods['price'],
            //         'multi_price' => (float)$goods['price'],
            //         'quantity' => $goods['quantity'],
            //         'spec_id_list'=> [943]
            //     ]
            // ], JSON_UNESCAPED_UNICODE)
        ];
        return $this->client->insertGoods($data);
    }

    /**
     * 更新商品库存
     * @param array $goodsInfo
     * @param array $pddGoods
     */
    public function editGoods($goods, $pddGoods)
    {
        $data = [
            'goods_id'              => $pddGoods['pdd_goods_id'],
            'modify_quantity_type'  => 2,
            'quantity'              => $goods['quantity'],
        ];
        return $this->client->editGoods($data);
    }

    public function orderAfterSale($params)
    {
        return Normal::returnCode(Normal::SUC, '售后成功');
    }
}